//
//  OYOauthController.swift
//  weiboCopycat
//
//  Created by Orange Yu on 2016/12/1.
//  Copyright © 2016年 Orange Yu. All rights reserved.
//

import UIKit
import SVProgressHUD

//let AppKey = "1963147634"
////  授权回调页
//let Redirect_uri = "http://www.itcast.cn"
//let AppSecret = "3ada504806e8d38441e9347aa814bcc4"

let AppKey = "4150402459"
let Redirect_uri = "https://github.com/superorangecc"
let AppSecret = "6eed0222b33b511dec7be98100a7906e"


class OYOauthController: UIViewController {
    
    lazy var webView: UIWebView = UIWebView()
    
    
    override func loadView() {
        
        webView.delegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        self.navigationItem.leftBarButtonItem  = UIBarButtonItem(title: "返回", target: self, action: #selector(dismissAction))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动保存", target: self, action: #selector(autoSavingAction))
        
        
        // 定义接口URL
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_uri)"
        
        let request:URLRequest = URLRequest(url: URL(string: urlStr)!)
        
        webView.loadRequest(request)
        
        
    }
    
    func dismissAction() {
        self.dismiss(animated: true, completion: nil)
    }
    
    func autoSavingAction() {
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = 'hao123guohaibin@163.com'; document.getElementById('passwd').value = 'guohaibin123'")
    }
    

    
}

extension OYOauthController:UIWebViewDelegate{
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 由于请求成功，同意授权之后会重定向到新的url请求，请求中包含code
        guard let url = request.url else { return false }
        
        // 代码运行到这里，代表url不为nil
        if !url.absoluteString.hasPrefix(Redirect_uri) {
            return true
        }
        
        // 代码运行到这里，代表返回授权码的url存在。如果url存在，则获取url里面的code
        // 1.获取url中含前缀的授权码
        if let query = url.query,query.hasPrefix("code=") {
            // 2.获取截取的起始index
            let index = "code=".endIndex
            // 3.获取code
            let code = query.substring(from: index)
            
            // 4.通过授权码发送请求获取accesstoken令牌
            OYUserInfoViewModel.sharedUserInfo.getAccessToken(code: code,callBack:{ (isSuccess) in
                if isSuccess {
                    print("登录成功")
                    self.dismiss(animated: false, completion: {
                        // 5.代码运行到这里登录成功，给appdelegate发送通知，切换根视图控制器
                        NotificationCenter.default.post(name: NSNotification.Name(SwitchRootViewController), object: self)
                    })
                }else {
                    
                    print("登录失败")
                }
            })
            
        }
        
        
        // 不加载页面
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
}
